//
//  CXPhotoAssetCell.swift
//  Asman
//
//  Created by 李旭峰 on 6/5/19.
//  Copyright © 2019 李旭峰. All rights reserved.
//

import UIKit
import AVKit
//import RxSwift
//import RxCocoa

@objc protocol CXPhotoAssetCellDelegate {
  func save(_ cell:CXPhotoAssetCell,withAsset asset:CXPhotoAsset)
  func save(_ cell:CXPhotoAssetCell,withImagePath imagePath:String)
  func save(_ cell:CXPhotoAssetCell,withImage image:UIImage)
  func save(_ cell:CXPhotoAssetCell,withVideoPath videoPath:String)
}

class CXPhotoAssetCell: UICollectionViewCell {
    var photoAsset:CXPhotoAsset?
    let imageView = UIImageView()
    let scrollView = UIScrollView()
    let videoBox = UIView()
    var playerItem:AVPlayerItem?
    var singTapAction:(()->())?
    weak var delegate:CXPhotoAssetCellDelegate?
    lazy var btnPlay:CXPowerButton = {
      let btn = CXPowerButton(type: .image)
      btn.addTarget(self, action: #selector(onClickedPlayButton), for: .touchUpInside)
      btn.iconLabel.openShadow = true
        // TODO:>
        btn.iconLabel.cxFont = FontAsset.PingFangSC_Regular.size(30)
//      btn.iconLabel.cxFont = FontAsset.Icon.size(60.0)
      btn.setIcon("\u{e710}", for: .normal)
      btn.setIconColor(UIColor.white, for: .normal)
      btn.paddingValue = UIEdgeInsets(top: 15.0, left: 15.0, bottom: 15.0, right: 15.0)
      btn.isHidden = true
      return btn
    }()
    lazy var player:AVPlayer = {
        let player = AVPlayer(playerItem: nil)
        player.addObserver(self, forKeyPath: "status", options: .new, context: nil)
        return player
    }()
    lazy var playerViewController:AVPlayerViewController = {
        let playerVC = AVPlayerViewController()
        playerVC.player = self.player
        return playerVC
    }()
    lazy var playerLayer:AVPlayerLayer = {
        let playerLayer = AVPlayerLayer(player: self.player)
        playerLayer.videoGravity = AVLayerVideoGravity.resizeAspect
        playerLayer.frame = UIScreen.main.bounds
        return playerLayer
    }()
  override init(frame: CGRect) {
    super.init(frame: frame)
    self.contentView.addSubview(self.playerViewController.view)
    self.playerViewController.view.snp.makeConstraints { (make) in
      make.centerX.width.equalToSuperview()
      make.top.height.equalToSuperview()
    }
    self.scrollView.zoomScale = 1
    self.scrollView.minimumZoomScale = 1
    self.scrollView.maximumZoomScale = 3
    self.scrollView.contentSize = CGSize.zero
    self.scrollView.delegate = self
    self.contentView.addSubview(self.scrollView)
    self.scrollView.snp.makeConstraints { (make) in
      make.left.right.top.bottom.equalToSuperview()
    }
    
    self.imageView.contentMode = .scaleAspectFit
    self.imageView.clipsToBounds = true
    self.scrollView.addSubview(self.imageView)
    
    /// 单击消失，双击放大
    let singTapGesture = UITapGestureRecognizer(target: self, action: #selector(ImagePickerPreviewCell.onImageSingleTap(_:)))
    singTapGesture.numberOfTapsRequired = 1
    singTapGesture.numberOfTouchesRequired = 1
    // 双击放大
    let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(ImagePickerPreviewCell.onImageDoubleTap(_:)))
    doubleTapGesture.numberOfTapsRequired = 2
    doubleTapGesture.numberOfTouchesRequired = 1
    singTapGesture.require(toFail: doubleTapGesture)
    // 长按保存
    let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(onImageLongPressGesture(_:)))
    longPressGesture.minimumPressDuration = 1
    longPressGesture.numberOfTouchesRequired = 1
    longPressGesture.allowableMovement = 15
    
    self.addGestureRecognizer(singTapGesture)
    self.addGestureRecognizer(doubleTapGesture)
    self.addGestureRecognizer(longPressGesture)
    
    self.contentView.addSubview(self.btnPlay)
    self.btnPlay.snp.makeConstraints { (make) in
      make.center.equalToSuperview()
    }
  }
  
  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  override func prepareForReuse() {
    self.player.pause()
    playerItem = nil
    imageView.image = nil
    photoAsset = nil
  }
  override func layoutSubviews() {
    super.layoutSubviews()
    switch self.photoAsset?.type {
    case .image?:
      scrollView.zoomScale = 1.0
      scrollView.contentSize = CGSize.zero
      if let _image = imageView.image {
        let bounds = UIScreen.main.compatibleBounds
        let boundsDept = bounds.width / bounds.height
        let imgDept = _image.size.width / _image.size.height
        // 图片长宽和屏幕的宽高进行比较 设定基准边
        if imgDept > boundsDept {
          imageView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.width / imgDept)
        } else {
          imageView.frame = CGRect(x: 0, y: 0, width: bounds.height * imgDept, height: bounds.height)
        }
        self.scrollView.layoutIfNeeded()
        self.scrollView.frame.origin = CGPoint.zero
        imageView.center = scrollView.center
      }
    case .video?:break
    default:break
    }
  }
    deinit {
        self.player.removeObserver(self, forKeyPath: "status")
    }
    func setupPhotoAsset(_ photoAsset:CXPhotoAsset){
      self.photoAsset = photoAsset
      if self.photoAsset == nil {
        self.playerItem = nil
        self.imageView.image = nil
        self.cx_removeLoading()
        return
      }
      self.imageView.alpha = 1.0
      if let tempAsset = self.photoAsset?.asset {
          if tempAsset.mediaType == .video {
            self.scrollView.isUserInteractionEnabled = false
            if let thumbnail = self.photoAsset?.thumbnail {
              self.imageView.image = thumbnail
            }else {
                tempAsset.getImageAsync {[weak self] (image) in
                    guard let `self` = self else { return }
                    guard let currentAsset = self.photoAsset?.asset else { return }
                    if currentAsset.localIdentifier != tempAsset.localIdentifier { return }
                    self.imageView.image = image
                    self.photoAsset?.thumbnail = image
                    self.layoutSubviews()
                    self.cx_removeLoading()
                }
            }
            tempAsset.getAVAssetAsync {[weak self] (avAsset) in
                guard let `self` = self else { return }
                guard let currentAsset = self.photoAsset?.asset else { return }
                if currentAsset.localIdentifier != tempAsset.localIdentifier { return }
                guard let tempAVAsset = avAsset else { return }
                self.playerViewController.view.isHidden = false
                let playerItem = AVPlayerItem(asset: tempAVAsset)// AVPlayerItem(url: URL(string: self.photoAsset!.path.analyseCnString())!)
                self.playerItem = playerItem
                self.player.replaceCurrentItem(with: self.playerItem!)
            }
        }else if tempAsset.mediaType == .image {
            self.cx_showLoading(with: "正在加载图片...")
            self.scrollView.isUserInteractionEnabled = true
            if self.photoAsset?.thumbnail != nil{
              self.imageView.image = self.photoAsset?.thumbnail
              self.cx_removeLoading()
              self.layoutSubviews()
            }else{
                tempAsset.getImageAsync {[weak self] (image) in
                    guard let `self` = self else { return }
                    guard let currentAsset = self.photoAsset?.asset else { return }
                    if currentAsset.localIdentifier != tempAsset.localIdentifier { return }
                    self.imageView.image = image
                    self.photoAsset?.thumbnail = image
                    self.layoutSubviews()
                    self.cx_removeLoading()
                }
            }
            self.playerViewController.view.isHidden = true
        }
        return
      }
      if self.photoAsset!.type == .video {
        self.scrollView.isUserInteractionEnabled = false
        if let thumbnail = self.photoAsset?.thumbnail {
          self.imageView.image = thumbnail
        }else{
          let videoUrl = URL(string: self.photoAsset?.path ?? "")
          self.imageView.sd_setVideoThumbnail(with: videoUrl) {[weak self] (image, url) in
            guard let `self` = self else { return }
            guard let tempVideoUrl = URL(string: self.photoAsset?.path ?? "") else { return }
            if tempVideoUrl != url { return }
            self.imageView.image = image
            self.photoAsset?.thumbnail = image
          }
        }
        self.playerViewController.view.isHidden = false
        let playerItem = AVPlayerItem(url: URL(string: self.photoAsset!.path.analyseCnString())!)
        self.playerItem = playerItem
        self.player.replaceCurrentItem(with: self.playerItem!)
      }
      else
      {
        self.cx_showLoading(with: "正在加载图片...")
        self.scrollView.isUserInteractionEnabled = true
        if self.photoAsset?.thumbnail != nil
        {
          self.imageView.image = self.photoAsset?.thumbnail
          self.cx_removeLoading()
          self.layoutSubviews()
        }
        else
        {
          self.imageView.sd_setImage(with: URL(string: self.photoAsset!.path.analyseCnString()))
          {[weak self] (image, error, cache, url) in
            guard let `self` = self else { return }
            guard let pathUrl = URL(string: self.photoAsset?.path.analyseCnString() ?? "") else { return }
            if pathUrl != url { return }
            self.imageView.image = image
            self.photoAsset?.thumbnail = image
            self.layoutSubviews()
            self.cx_removeLoading()
          }
        }
        self.playerViewController.view.isHidden = true
      }
    }
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "status" && object is AVPlayer{
            switch self.player.status {
            case .readyToPlay:
                UIView.animate(withDuration: 0.3) {
                    self.imageView.alpha = 0.0
                }
            case .failed:break
            case .unknown:break
            default:break
            }
        }
    }
  
  func setSingTapAction(action:(()->())?){
    self.singTapAction = action
  }
  @objc func onImageSingleTap(_ sender:UITapGestureRecognizer) {
    self.singTapAction?()
  }
  @objc func onImageDoubleTap(_ sender:UITapGestureRecognizer) {
    let zoomScale = self.scrollView.zoomScale
    if zoomScale <= 1.0 {
      let loc = sender.location(in: sender.view) as CGPoint
      let wh:CGFloat = 1
      let x:CGFloat = loc.x - 0.5
      let y:CGFloat = loc.y - 0.5
      let rect = CGRect(x: x, y: y, width: wh, height: wh)
      self.scrollView.zoom(to: rect, animated: true)
    } else {
      self.scrollView.setZoomScale(1.0, animated: true)
    }
  }
  @objc func onImageLongPressGesture(_ sender:UILongPressGestureRecognizer){
    if sender.state == .began {
      print("长按手势被触发,\(sender.state)")
      switch self.photoAsset?.type {
      case .video?:self.saveVideo(photoAsset: self.photoAsset!)
      case .image?:self.saveImage(photoAsset: self.photoAsset!)
      default:break
      }
    }
  }
  @objc func onClickedPlayButton(){
    self.playerViewController.player?.play()
  }
  func pause(){
    if self.photoAsset?.type == .some(.video) {
      self.player.pause()
    }
  }
  func didScroll(){
    
  }
  func didEndScroll(){
    
  }
  private func saveImage(photoAsset:CXPhotoAsset){
    if photoAsset.path.count < 5 {
      if let image = photoAsset.thumbnail {
        self.delegate?.save(self, withImage: image)
      }
      return
    }
    self.delegate?.save(self, withImagePath: photoAsset.path)
  }
  private func saveVideo(photoAsset:CXPhotoAsset){
    guard photoAsset.path.count >= 4 else {
      return
    }
    self.delegate?.save(self, withVideoPath: photoAsset.path)
  }
}
extension CXPhotoAssetCell : UIScrollViewDelegate {
  /// 固定imageview，始终整个content的剧中位置
  func scrollViewDidZoom(_ scrollView: UIScrollView) {
    var xcenter = scrollView.center.x
    var ycenter = scrollView.center.y
    
    xcenter = scrollView.contentSize.width > scrollView.frame.size.width ? scrollView.contentSize.width/2 : xcenter
    
    ycenter = scrollView.contentSize.height > scrollView.frame.size.height ? scrollView.contentSize.height/2 : ycenter
    imageView.center = CGPoint(x: xcenter, y: ycenter)
  }
  
  /// 返回放置在scrollview中的子视图
  func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return imageView
  }
}
